import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    TextInput,
    AsyncStorage,
    DeviceEventEmitter,
    StatusBar,
    Platform,
} from 'react-native';
import {Toast,ModalIndicator} from 'teaset';
import Utils from'../../common/Utils'
import Config from '../../common/Config'
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
export default class SetLabelPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "coverId":this.props.id
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/directories/getInfo',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    if(responseJson.data.remarkVO===null){
                        this.setState({
                            labelMsg:null,
                            label:null
                        })
                    }else {
                        if(responseJson.data.remarkVO.label!==null){
                            this.setState({
                                label:responseJson.data.remarkVO.label,
                                labelMsg:responseJson.data.remarkVO.label,
                            })
                        }else {
                            this.setState({
                                label:null,
                                labelMsg:null
                            })
                        }
                    }
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            status:false,
            labelMsg:'',
            token:'',
            label:null
        }
    };

    addLabel=()=>{
        this.phoneTextInput.blur();
        let params={
            "token":this.state.token,
            "coverId":this.props.id,
            "label":this.state.labelMsg
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/directories/updateRemark',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    Actions.pop();
                    Actions.refresh({phone:this.props.phone,nickname:this.props.nickname});
                    DeviceEventEmitter.emit('refreshed','aaa');
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"
                />
                <View style={styles.titleView}>
                    {alert(this.props.nickname)}
                    <TouchableOpacity
                        onPress={()=>Actions.pop()&&DeviceEventEmitter.emit('refreshed','aaa')}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.WhiteGoBack}
                            style={styles.goBackImg}/>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>设置标签</Text>
                    <TouchableOpacity
                        onPress={()=>this.addLabel()}
                        style={styles.completeView}>
                        <Text style={[styles.titleMsg,{marginBottom:Platform.OS==='ios'?29/2:10}]}>完成</Text>
                    </TouchableOpacity>
                </View>
                {this.state.label!==null&&this.state.label!=''
                    ?(<View>
                        <View style={{height:45,backgroundColor:'#ffffff'}}>
                            <TextInput ref={ (ref)=>this.phoneTextInput = ref }
                                       autoCapitalize={"none"}
                                       underlineColorAndroid={'transparent'}
                                       style={{height:45,fontSize:14,marginLeft:15,width:width}}
                                       placeholder="输入标签"
                                       defaultValue={this.state.labelMsg}
                                       autoFocus={true}
                                       placeholderTextColor='#b2b2b2'
                                       autoCorrect={false}
                                       onChangeText={(text)=>{
                                           this.setState({
                                               labelMsg:text,
                                           });
                                       }}/>
                        </View>
                        <View>
                            <Text style={{marginLeft:15,marginTop:10,fontSize:14,color:'#646464'}}>所有标签</Text>
                            <View>
                                <View style={{marginLeft:15,height:24,borderColor:'#3090dd',justifyContent:'center',flex:0,
                                    borderRadius:12,borderWidth:1,marginTop:10}}>
                                    <Text style={{marginLeft:7,marginRight:7,fontSize:14,color:'#3090dd'}}>{this.state.label}</Text>
                                </View>
                            </View>
                        </View>
                    </View>)
                    :(<View>
                        <TextInput ref={ (ref)=>this.phoneTextInput = ref }
                                   autoCapitalize={"none"}
                                   underlineColorAndroid={'transparent'}
                                   style={{height:45,width:width,backgroundColor:'#ffffff',fontSize:14,paddingLeft:15}}
                                   placeholder="输入标签"
                                   autoFocus={true}
                                   placeholderTextColor='#b2b2b2'
                                   autoCorrect={false}
                                   onChangeText={(text)=>{
                                       this.setState({
                                           labelMsg:text,
                                       });
                                   }}/>
                    </View>)}
            </View>

        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        fontSize:17,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?65/2:25/2,left:15,
    },
    goBackImg:{
        height:18,
        width:18
    },
    completeView:{
        position: 'absolute',
        right:15,bottom:0
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderColor:'#e3e3e4',
        alignItems:'center',
        flexDirection:'row'
    },
    labelMsg:{
        marginLeft:15,
        color:'#b2b2b2',
        fontSize:14
    },
    textInputView:{
        marginLeft:7,
        color:'#000000',
        fontSize:14,
        justifyContent:'center',
        marginRight:7,
    },
    iconView:{
        flexDirection:'row',
        marginTop:14
    }
});
